//
//  MASExampleAutoAddView.m
//  MasonryExample
//
//  Created by 山刘 on 2020/6/10.
//  Copyright © 2020 山刘. All rights reserved.
//

#import "MASExampleAutoAddView.h"

static UIEdgeInsets padding;
static CGFloat height = 100;
static int num = 0;

@interface MASExampleAutoAddView()
@property (nonatomic, strong) UIView *superView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, weak) MASConstraint *bottomConstraint;
@end


@implementation MASExampleAutoAddView
- (id)init {
    self = [super init];
    if (!self) return nil;
    padding = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.superView = [LayoutUtils createView];
    [self addSubview:self.superView];
    [self.superView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(padding);
    }];
    
    UIButton *tapButton = [LayoutUtils createButtonWithTitle:@"Add" target:self selector:@selector(clickButton:)];
    [self.superView addSubview:tapButton];
    [tapButton makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(padding);
        self.bottomConstraint = make.bottom.mas_equalTo(padding);//记录下这个约束对象
        make.height.equalTo(@(height));
    }];
    self.bottomView = tapButton;
    
    UIView *bottomView = [LayoutUtils createView];
    [self.superView addSubview:bottomView];
    [bottomView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(padding);
        make.top.mas_equalTo(self.superView.mas_bottom).mas_equalTo(padding);
        make.height.mas_equalTo(@(height));
    }];
    
    return self;
}

-(void)clickButton:(UIButton*)sender{
    [self.bottomConstraint uninstall];//卸载旧的底部约束
    num += 1;
    UILabel *label = [LayoutUtils fixedLabelWithText:[NSString stringWithFormat:@"控件%d", num]];
    [self.superView addSubview:label];
    [label makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(padding);
        make.top.equalTo(self.bottomView.mas_bottom).mas_equalTo(padding);
        self.bottomConstraint = make.bottom.equalTo(self.superView.mas_bottom).mas_equalTo(padding);//添加新的底部约束
        make.height.equalTo(@(height));
    }];
    self.bottomView = label;
}
@end
